import React, {Component} from 'react';

import logo from './logo.svg';
import ajax from './utils/ajax';
import './App.css';
import {URL} from './config/config';
import {connect} from 'react-redux';
import {increment, incrementSync} from './actions/counter';
import {
    Table,
    Popconfirm,
    Button,
    Modal,
    Icon,
    Transfer,
    Select,
    Form,
    Layout,
    Row,
    Drawer,
    Col,
    Input,
    Divider
} from 'antd';
import * as style from './style.scss';
import {message} from 'antd';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            targetKeys: [],
            i: 0,
            zipId: "test.zip",
            selectArr: [{tableName: 3, delName: 2}, {tableName: 1, delName: 2}],
            visible: false,
            placement: 'right',
            schemaList: [{id: 1, name: 1}],
            allTable: [{
                key: 1,
                name: `请选择数据库`

            }]
        };
        this.handleChangeSelect = this.handleChangeSelect.bind(this);
        this.handleBlur = this.handleBlur.bind(this);
        this.handleFocus = this.handleFocus.bind(this);
        this.getMock = this.getMock.bind(this);
        this.renderFooter = this.renderFooter.bind(this);
        this.renderFooter = this.renderFooter.bind(this);
        //handleChange
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleGenerateFile = this.handleGenerateFile.bind(this);
    }

    handleGenerateFile() {
        this.props.form.validateFields(['dbName', 'tableNames'], (err) => {
            if (!err) {

            }
        });
    }

    handleChangeSelect(value) {
        console.log(`selected ${value}`);
        const _this = this;
        ajax({
            url: `${URL}/base/getAllTableNameBySchema`,
            data: {"name": value}
        }).then((a) => {

            const result = a.body.value.map(x => {
                return {...x, key: x.name}
            });
            _this.setState({allTable: result})
        }, (b) => {
            console.log('fail', b);
        });
    }


    handleBlur() {
        console.log('blur');
    }

    handleFocus() {
        console.log('focus');
    }

    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        console.info(this.props.form.getFieldsValue());
        const result = this.props.form.getFieldsValue();
        for (var i in result) {
            if (!result[i]) {
                message.error(`${i} is null`);
                return;
            }
            ;
        }
        ajax({
            url: `${URL}/base/testFTL`,
            data: result
        }).then((a) => {
            //  _this.state.zipId=a;
            console.info(a);
            console.info(a.text.url);
            var urlObj = eval('(' + a.text + ')');
            console.info("abcd");
            _this.setState({
                zipId: urlObj.url
            });
            _this.setState({
                visible: true
            });
        }, (b) => {
            console.log('fail', b);
        });
    }


    getMock() {
        const mockData = [];
        this.setState({mockData});
    }

    handleChange(targetKeys) {
        this.setState({targetKeys});

        let newArr = [];
        targetKeys.map((val, index) => {
            newArr.push({tableName: val, delName: ""})
        })


        this.setState({selectArr: newArr});
        console.info(`targetKeys`)
    }

    renderFooter() {
        return (
            <Button
                size="small"
                style={{float: 'right', margin: 5}}
                onClick={this.getMock}
            >
                reload
            </Button>
        );
    }

    changeDelName(_this, tableName, event) {
        console.info(tableName);
        console.info(event.target.value);
        let newArr = [];
        this.state.selectArr.map((val, index) => {
            if(val.tableName==tableName){
                val.delName=event.target.value;
            }

        })
    }

    onClose = () => {
        this.setState({
            visible: false,
        });
    };
    showDrawer = () => {
        this.setState({
            visible: true,
        });
    };

    componentDidMount() {
        this.getMock();
        const _this = this;
        ajax({
            url: `${URL}/base/getAllSchema`,
            data: {
                "username": "wb_yanghui001"
            }
        }).then((a) => {
            console.info(a.body.value);
            const result = a.body.value.map(x => {
                return {...x, id: x.name}
            });
            _this.setState({schemaList: result})
        }, (b) => {
            console.log('fail', b);
        });
    }

    render() {
        const {Header, Content} = Layout;
        const Search = Input.Search;

        const FormItem = Form.Item;
        const formItemLayout = {
            labelCol: {span: 7},
            wrapperCol: {span: 17}
        };
        const expandPersonSetting = false;
        let options = this.state.schemaList.map(d => <Select.Option key={d.id}>{d.name}</Select.Option>);
        const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
        return (
            <div className="App">
                <Drawer
                    title="下载"
                    placement={this.state.placement}
                    closable={false}
                    onClose={this.onClose}
                    visible={this.state.visible}
                >
                    < a href={this.state.zipId} download={true}>下载</ a>
                    <p>该文件会每天清理</p>
                </Drawer>
                <Form onSubmit={this.handleSubmit}>
                    <Layout>
                        <Header style={{background: '#f0f2f5', padding: 0}}>
                        </Header>
                        <Content>
                            <Row gutter={16}>
                                <Col span={11} key='mapperSuffix'>
                                    <FormItem key='mapperSuffix' {...formItemLayout} label='Mapper Interface 后缀:'>
                                        {getFieldDecorator('mapperSuffix', {
                                            initialValue: "Mapper"
                                        })(
                                            <Input placeholder='设置Mapper Interfact后缀，默认：UserDOMapper'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={11} key='mapperInterfacePackageName'>
                                    <FormItem key='mapperInterfacePackageName' {...formItemLayout}
                                              label='Mapper Interface 包名:'>
                                        {getFieldDecorator('mapperInterfacePackageName', {
                                            initialValue: 'com.xrzw.user.generate.dao'
                                        })(
                                            <Input placeholder='like: com.xrzw.generate.dao'/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={11} key='mapperXMLPackageName'>
                                    <FormItem key='mapperXMLPackageName' {...formItemLayout} label='Mapper XML 文件包名:'>
                                        {getFieldDecorator('mapperXMLPackageName', {
                                            initialValue: "com.xrzw.user.generate.mapper"
                                        })(
                                            <Input placeholder='like: mybatis.mapper.user'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={11} key='mapperInterfaceParentName'>
                                    <FormItem key='mapperInterfaceParentName' {...formItemLayout}
                                              label='Mapper Interface 父类:'>
                                        {getFieldDecorator('mapperInterfaceParentName', {
                                            initialValue: "com.linkafri.generate.code.mapper.CrudMapper"
                                        })(
                                            <Input placeholder='like: "com.linkafri.generate.code.mapper.CrudMapper"'/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={11} key='entityPackageName'>
                                    <FormItem key='entityPackageName' {...formItemLayout} label='实体类包名:'>
                                        {getFieldDecorator('entityPackageName', {
                                            initialValue: "com.xrzw.user.generate.bean"
                                        })(
                                            <Input placeholder='like: com.linkafri.generate.code.bean'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={11} key='entityParent'>
                                    <FormItem key='entityParent' {...formItemLayout} label='实体类父类:'>
                                        {getFieldDecorator('entityParent', {
                                            initialValue: "com.linkafri.generate.code.bean.AuditEntity"
                                        })(
                                            <Input placeholder='like: com.linkafri.generate.code.bean.AuditEntity'/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={11} key='author'>
                                    <FormItem key='author' {...formItemLayout} label='用户姓名:'>
                                        {getFieldDecorator('author', {
                                            initialValue: "yangh0597@gmail.com"
                                        })(
                                            <Input placeholder='请输入用户姓名'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={11} key='curdPackageName'>
                                    <FormItem key='curdPackageName' {...formItemLayout} label='CRUD业务包名:'>
                                        {getFieldDecorator('curdPackageName', {
                                            initialValue: "com.xrzw.user.generate"
                                        })(
                                            <Input placeholder='like: "com.linkafri.generate.code"'/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={11} key='removeEntityPrefix'>
                                    <FormItem key='removeEntityPrefix' {...formItemLayout} label='移除掉实体类前缀:'>
                                        {getFieldDecorator('removeEntityPrefix', {
                                            initialValue: 'xrzw_'
                                        })(
                                            <Input placeholder='移除掉实体类前缀，默认：无'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={11} key='delName'>
                                    <FormItem key='delName' {...formItemLayout} label='逻辑删除字段名称:'>
                                        {getFieldDecorator('delName', {
                                            initialValue: 'is_delete'
                                        })(
                                            <Input placeholder='逻辑删除字段名称，默认：无'/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} key='delNames'>
                                    <FormItem key='delNames' {...formItemLayout} label=''>
                                        {getFieldDecorator('delNames', {
                                            initialValue: this.state.selectArr
                                        })(
                                            <Input placeholder='逻辑删除字段名称，默认：无' type="hidden"/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>

                        </Content>
                    </Layout>


                    <Layout>
                        <br/>
                        <Row>
                            <Col span={5} className={style["demo-nav"]}>

                            </Col>
                            <Col span={4}>
                                <FormItem key='schemaName'>
                                    {getFieldDecorator('schemaName', {
                                        valuePropName: 'setFieldsValue'

                                    })(
                                        <Select
                                            showSearch
                                            style={{width: 200}}
                                            placeholder="Select a schema"
                                            optionFilterProp="children"
                                            onChange={this.handleChangeSelect}
                                            onFocus={this.handleFocus}
                                            onBlur={this.handleBlur}
                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        >
                                            {options}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={13}>

                                <FormItem>
                                    <Button type="primary" htmlType="submit">提交</Button>
                                </FormItem>

                            </Col>
                            <Col span={2}>

                            </Col>
                        </Row>
                        <Row align="middle">
                            <Col span={2}></Col>
                            <Col span={22}>
                                <Row>
                                    <Col span={19}>
                                        <FormItem key='tableNameList'>
                                            {getFieldDecorator('tableNameList', {
                                                valuePropName: 'setFieldsValue'
                                            })(
                                                <Transfer
                                                    dataSource={this.state.allTable}
                                                    showSearch
                                                    listStyle={{
                                                        width: 250,
                                                        height: 350,
                                                    }}
                                                    operations={['走你 到右边去', '走你 到左边去']}
                                                    targetKeys={this.state.targetKeys}
                                                    onChange={this.handleChange}
                                                    render={item => `${item.name}`}
                                                    footer={this.renderFooter}
                                                    style={{marginLeft: 16}}
                                                />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={5}>
                                        {

                                            this.state.selectArr.map((item, index) => {
                                                return (
                                                    // <Input placeholder={"请输入"+item.tableName+"的逻辑删除字段"} value={item.delName}/>

                                                    <Input
                                                        placeholder={"请输入" + this.state.selectArr[index].tableName + "的逻辑删除字段(如果没有请忽略)"}
                                                        onChange={this.changeDelName.bind(this, 1111, this.state.selectArr[index].tableName)}/>

                                                )


                                            })}

                                    </Col>
                                </Row>
                            </Col>

                        </Row>
                    </Layout>
                </Form>
            </div>
        );
    }
}

const
    app = Form.create()(App);
const mapStateToProps = (state) => {
    return {
        counter: state.counter
    };
};

export default connect(mapStateToProps, {increment, incrementSync})(app);